package com.meichis.yndms.ui.activity;

import android.content.Intent;
import android.view.View;

import androidx.core.view.GravityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;

import com.meichis.mcsappframework.dialog.AppUpdateDialog;
import com.meichis.mcsappframework.dialog.CustomMessageDialog;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.mcsappframework.utils.StatusBarUtil;
import com.meichis.yndms.R;
import com.meichis.yndms.databinding.ActivityMainTabBinding;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.ui.fragment.DataCentreFragment;
import com.meichis.yndms.ui.fragment.HomeFragment;
import com.meichis.yndms.ui.fragment.NoticeFragment;
import com.meichis.yndms.vm.MainVM;
import com.meichis.yndms.vm.SyncBaseDataPresenter;

public class MainTabActivity extends BaseActivity {

    private ActivityMainTabBinding binding;
    private MainVM vm;

    @Override
    protected void beforeInit() {
        super.beforeInit();
        StatusBarUtil.setTranslucentStatus(this);
    }

    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main_tab);
        vm = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MainVM.class);
        binding.setVm(vm);
        binding.setClick(new ClickEvent());
        binding.setLifecycleOwner(this);
    }

    @Override
    protected void init() {
        binding.vp.setAdapter(vpUnLoginAdapter);
        binding.vp.addOnPageChangeListener(vpCahangeListener);
        binding.vp.setOffscreenPageLimit(3);
        binding.tvHome.setSelected(true);
        addObserver();
        vm.GetOverview();
        //上传广播
        sendBroadcast(new Intent("com.meichis.yndms.intent.UpLoadInfo"));
        new SyncBaseDataPresenter().sync();
        vm.GetAttachmentDownloadURL();
    }

    @Override
    protected void onResume() {
        super.onResume();
        vm.GetUnReadNotice();
    }

    private void addObserver() {

        vm.getShowDialog().observe(this, (aBoolean) -> showLoading(aBoolean));


        vm.getAppVersion().observe(this, appVersion -> {
            if (appVersion != null) {
                AppUpdateDialog updateDialog = new AppUpdateDialog(MainTabActivity.this, appVersion, aVoid -> null);
                updateDialog.show();
            }
        });

        vm.getNoticeList().observe(this, notices -> {
            if (notices.size() > 0) {
                MessageTools.ShowmessageDialog(getActivity(), "您有" + notices.size() + "条未读公告", "查看", () -> {
                    binding.tvHome.setSelected(false);
                    binding.tvNotice.setSelected(true);
                    //使Viewpager展示当前选中的项
                    binding.vp.setCurrentItem(Integer.parseInt((String) binding.tvNotice.getTag()));//将标志从身体里取出来
                });
            } else {
                vm.GetFeedbackPopCount();
            }
        });

        vm.getFeedBackCount().observe(this, integer -> {
            if (integer > 0) {
                if (vm.getHasShowFeedBackDialog().getValue()) {
                    return;
                }
                MessageTools.ShowmessageDialog(getActivity(), "您有" + integer + "条伊利牛奶平台小程序消息待处理", "查看",
                        "忽略", () -> openActivity(TerminalFeedbackListActivity.class), () -> {
                        });
                vm.getHasShowFeedBackDialog().setValue(true);
            }
        });
    }


    @Override
    public void onBackPressed() {
        util.remove(SharePreferenceUtil.PREFERENCES_AUTOLOGIN);
        util.remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
        MessageTools.ShowFinishMessage(MainTabActivity.this, "请确认是否退出应用？");
    }


    //viewPager适配器
    FragmentStatePagerAdapter vpUnLoginAdapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new HomeFragment();
                case 1:
                    return new DataCentreFragment();
                case 2:
                    return new NoticeFragment();
                default:
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }
    };

    //ViewPager页面改动监听
    ViewPager.OnPageChangeListener vpCahangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            //切换到目标页面时，所有tv恢复初始状态
            initTvMenu();
            switch (position) {
                case 0:
                    binding.tvHome.setSelected(true);
                    break;
                case 1:
                    binding.tvDataCenter.setSelected(true);
                    break;
                case 2:
                    binding.tvNotice.setSelected(true);
                    break;

            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    private void initTvMenu() {
        binding.tvHome.setSelected(false);
        binding.tvDataCenter.setSelected(false);
        binding.tvNotice.setSelected(false);
    }

    public class ClickEvent {

        public void onback() {
            onBackPressed();
        }

        public void personCenter() {
            if (binding.mainDrawerLayout.isDrawerOpen(GravityCompat.END)) {
                binding.mainDrawerLayout.closeDrawer(GravityCompat.END);
            } else {
                binding.mainDrawerLayout.openDrawer(GravityCompat.END);
            }
        }

        public void onCheckUpdate() {
            vm.CheckUpdate();
        }

        public void onMenuClick(View view) {
            initTvMenu();
            view.setSelected(true);
            //使Viewpager展示当前选中的项
            binding.vp.setCurrentItem(Integer.parseInt((String) view.getTag()));//将标志从身体里取出来
        }
    }
}
